library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity clk_gen is
    generic (div_factor_width: natural := 6);
    port (
        clkin: in std_logic;
        div_factor:in std_logic_vector(div_factor_width - 1 downto 0);
        div_en:in std_logic;
		div_en_ack: out std_logic;
        adc_clk: out std_logic;
        scope_clk: out std_logic;
        rst: in std_logic
    );
end clk_gen;
architecture rtl of clk_gen is
component pll IS
	PORT
	(
		inclk0		: IN STD_LOGIC  := '0';
		c0		: OUT STD_LOGIC 
	);
end component;
component rst_ctrl is
	port (
		rst_in: in std_logic;
		clk: in std_logic;
		rst_out: out std_logic;
		nrst_out: out std_logic
	);
end component;
signal clk_200mhz:std_logic;
signal rst_200mhz:std_logic;
signal counter: std_logic_vector(div_factor_width - 1 downto 0);
signal div_en_ff1,div_en_200mhz:std_logic; 
signal div_en_ack_ff0,div_en_ack_ff1:std_logic;
signal clk_100mhz,div_clk:std_logic:= '0';
begin
    adc_clk <= clk_100mhz;
    scope_clk <= div_clk;
	div_en_ack <= div_en_ack_ff1;
    U1: pll port map (
        inclk0 => clkin,
        c0 => clk_200mhz
    );
    U2: rst_ctrl port map(
        rst_in => rst,
        clk => clk_200mhz,
        rst_out => rst_200mhz,
        nrst_out => open
    );
	process(clkin)
	begin
		if(clkin = '1' and clkin'event) then
			div_en_ack_ff0 <= div_en_200mhz;
			div_en_ack_ff1 <= div_en_ack_ff0;
		end if;
	end process;
    process(clk_200mhz)
    begin
        if(clk_200mhz = '1' and clk_200mhz'event)then
            clk_100mhz <= not clk_100mhz;
            div_en_ff1 <= div_en;
            div_en_200mhz <= div_en_ff1;
        end if;
    end process;
    process(clk_200mhz,rst_200mhz)
    begin
        if(rst_200mhz = '1') then
            counter <= (others => '0');
            div_clk <= '0';
        elsif(clk_200mhz = '1' and clk_200mhz'event) then
            if(div_en_200mhz = '1') then
                if(counter = div_factor) then
                    counter <= (others => '0');
                    div_clk <= not div_clk;
                else
                    counter <= counter + 1;
                end if;
            end if;
        end if;
    end process;
end rtl;